/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libase.web.jsf.bean;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Named;
import libase.entity.Book;
import libase.entity.Exemplar;

/**
 *
 * @author aspr0
 */
@Named
@Stateless
public class ExemplarBean extends AbstractBean
{
    private Exemplar e = new Exemplar();

    public Exemplar getE()
    {
        if (fetchId())
        {
            return e = em.find(Exemplar.class, id);
        }

        return e;
    }

    public void setE(Exemplar e)
    {
        this.e = e;
    }

    public List<Exemplar> getExemplars()
    {
        return em.createNamedQuery("Exemplar.findAll").getResultList();
    }

    public List<Exemplar> getExemplarsByBook()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Exemplar.findByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Exemplar>();
        }
    }

    public List<Exemplar> getExemplarsByBookAvailable()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Exemplar.findAvailableByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Exemplar>();
        }
    }

    public List<Exemplar> getExemplarsByBookLeased()
    {
        if (fetchNamedId("bid"))
        {
            return em.createNamedQuery("Exemplar.findLeasedByBook").setParameter("book", new Book(nId)).getResultList();
        }
        else
        {
            return new LinkedList<Exemplar>();
        }
    }

    public Long countAvail(BigDecimal id)
    {
        return (Long) em.createNamedQuery("Exemplar.countAvailable").setParameter("book", new Book(id))
                .getResultList().get(0);
    }

    public Long countLeased(BigDecimal id)
    {
        return (Long) em.createNamedQuery("Exemplar.countLeased").setParameter("book", new Book(id))
                .getResultList().get(0);
    }

    public void create()
    {
        if (fetchNamedId("bid"))
        {
            e.setBook(new Book(nId));
            em.persist(e);
        }
        e = new Exemplar();
    }

    public void edit()
    {
        em.merge(e);
        e = new Exemplar();
    }

    public void remove()
    {
        getE();
        em.remove(e);
        e = new Exemplar();
    }
}
